<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>商品详情页</title>
    <link rel="stylesheet" href="/css/item.css">
    <link rel="stylesheet" href="/css/index.css">
    <link href="/bootstrap/css/bootstrap.min.css" rel="stylesheet">
</head>

<body style="background: #f5f5f5">
<div class="dingbu">
    <div class="denglu-font top">
        <!--        <a href="/" id="dingbuhome"><img src="/images/logo.jpg"></a>-->

        <!--        <div id="so" style="position: relative; left: 350px;top:8px;width: 100px; float: left;" class="top">-->
        <!--            <div class="input-group">-->
        <!--                <input type="text" class="form-control" id="searchText" style="width: 380px;">-->
        <!--                <span class="input-group-addon" id="search" onclick="search()"><i class="glyphicon glyphicon-search"-->
        <!--                                                                                  style="color: #0055aa;"> <span>搜索</span></i></span>-->
        <!--            </div>-->
        <!--        </div>-->
        <div class="denglu-font2 top">
            <a href="/" id="dingbuhome">返回首页</a>
            <a href="/" id="wants">发布求购</a>
            <a href="/" id="cart">我的购物车</a>
            <a href="#" id="release">发布商品</a>
            <a href="#" id="uname">zyl</a>
            <a href="login" id="login_logout">登录</a>
        </div>
        <div style="clear:both"></div>

    </div>
</div>

<!--<div class="list-1">-->
<!--    <ul class="list-ul-2" style="position: relative;right: 190px;">-->
<!--        <div class="img"><img src="/images/logo1.jpg" width="55px" height="55px" class="img-logo"/></div>-->

<!--        <li>-->
<!--            <a href="/" class="index_click">全部商品</a>-->
<!--        </li>-->
<!--        <li th:each="category:${categories}">-->
<!--            <a th:href="'/api/category/find?categoryId='+${category.id}" th:text="${category.name}"-->
<!--               class="category_click">123</a>-->
<!--        </li>-->
<!--    </ul>-->
<!--</div>-->
<div class="item-title">
    <h2 th:text="${item.itemName}"></h2>
    <div class="star">
        <button type="button" class="btn btn-default" id="btn_follow" style="margin-right: 10px">
            <span class="glyphicon glyphicon-star-empty" id="btn_follow_icon" aria-hidden="true"></span>关注卖家
        </button>
        <button type="button" class="btn btn-default" id="btn_collect">
            <span class="glyphicon glyphicon-star-empty" id="btn_collect_icon" aria-hidden="true"></span>收藏商品
        </button>
    </div>
</div>

<div id="itemboard" class="board">
    <div class="imge">
        <img th:src="${item.image}" class="itemimage">
    </div>

    <div id="details" class="details">
        <div style="height: 390px">
            <h1 id="itemname" class="itemname" th:text="${item.itemName}"
                style="font-size: 24px;font-weight: 400;"></h1>
            <h3 class="sellInfo" th:text="'已经销售：' + ${item.sales} + '件商品，剩余' + ${item.count} + '件商品'">暂无销售信息</h3>
            <div th:if="${item.level} eq 10">
                <h1 class="level" th:text="${item.level} + '成新'">全新！</h1>
            </div>
            <div th:if="${item.level} ne 10">
                <h1 class="level" th:text="${item.level} + '成新'">全新！</h1>
            </div>
            <h3 class="sellerName" th:text="'卖家：' + ${item.user.username}"></h3>
            <div class="line"></div>
            <h1 class="price" th:text="'￥' + ${item.price}">￥9999</h1>
            <!--        <div></div>-->
            <!--        <div th:if="${inCart} eq false">-->
            <!--            <input type="button" class="buybutton" value="加入购物车">-->
            <!--        </div>-->

            <!--        <div th:if="${inCart} eq true">-->
            <!--            <input type="button" class="incartbutton" value="已在购物车中" disabled>-->
            <!--        </div>-->
        </div>
        <div>
            <div><input type="button" class="buy-button" value="立即购买"></div>
            <div><input type="button" class="car-button" value="加入购物车"></div>
            <div th:if="${inCart} eq true"><input type="button" class="car-button" value="已在购物车中" disabled></div>
        </div>
    </div>

</div>
<div class="container">
    <h2>商品描述</h2>
    <div style="padding: 10px 40px">
        <span class="itemdescription" th:text="${item.description}">暂无商品的描述信息</span></div>
</div>

<div class="container" style="height: 230px">
    <div>
        <h2>评论</h2>
    </div>
    <div class="comment-send" style="width: 100%">
        <div id="commentForm" method="GET">
            <textarea class="comment-send-input" name="comment" form="commentForm" cols="30" rows="5"
                      id="commentboard" style="width: 980px"
                      placeholder="请自觉遵守互联网相关的政策法规，严禁发布色情、暴力、反动的言论。"></textarea>
        </div>
        <div><input class="comment-send-button" type="submit" value="发表评论">
        </div>
    </div>

    <div class="comment-list" id="commentList">

        <div th:each="comment:${comments}" class="comment comment-bottom">
            <div class="comment-content">

                <p class="comment-content-name" th:text="${comment.user.username}">Leon</p>

                <p class="comment-content-article" th:text="${comment.content}">Hello World!</p>

                <p class="comment-content-footer">
                        <span class="comment-content-footer-timestamp" th:text="${comment.createTime}">2020-08-08
                            10:08</span>
                </p>
            </div>

            <div class="cls"></div>
        </div>
    </div>
</div>

<script src="/jquery/jquery2.1.4.js"></script>
<script src="/bootstrap/js/bootstrap.js"></script>
<script src="/layer/layer.js"></script>
<script th:inline="javascript">
    function search() {
        console.log($('#searchText').val())
        var data = $('#searchText').val()
        location.assign('/search?keyword=' + data)
    }

    $('#login_logout').click(function () {
        localStorage.clear()
    })

    var itemId = 0
    itemId = [[${item.id}]]

    var userId = localStorage.getItem('userId')

    console.log(userId)

    $(function () {
        load_data()
        load_collect()
        $('.car-button').on('click', function () {
            if (userId == null || userId == '') {
                layer.msg('请先登录再添加购物车')
                return
            } else if (itemId == null || itemId == '') {
                layer.msg('暂无此商品信息，无法添加购物车')
                return
            }
            $.ajax({
                type: 'POST',
                dataType: 'json',
                url: '/api/cart/add?itemId=' + itemId + '&userId=' + userId + '&count=1',
                contentType: 'application/json',
                traditional: true,
                data: JSON.stringify(''),
                success: function (data) {
                    if (data.code == 0) {
                        layer.msg('添加购物车成功')
                    } else {
                        layer.msg(data.msg)
                    }
                },
                error: function (data) {
                }
            })
            $(this).val('已在购物车中')
            $(this).attr('disabled', true)
            $(this).css('background-color', '#6d757a')
        })

        $('.comment-send-button').on('click', function () {
            var content = $('#commentboard').val()
            if (userId == null || userId == '') {
                layer.msg('请先登录再进行评论')
                return
            } else if (itemId == null || itemId == '') {
                layer.msg('暂无此商品信息，无法添加评论')
                return
            } else if (content == null || content == '') {
                layer.msg('请输入评论内容')
                return
            }
            $.ajax({
                type: 'POST',
                dataType: 'json',
                url: '/api/comment/item?itemId=' + itemId,
                contentType: 'application/json',
                traditional: true,
                data: JSON.stringify({'userId': userId, 'content': content}),
                success: function (data) {
                    location.reload()
                    // location.href(data);
                    // if (data.code == 0) {
                    //     layer.msg("添加评论成功");
                    // } else {
                    //     layer.msg("添加评论失败");
                    // }
                },
                error: function (data) {
                    location.reload()
                    // layer.msg("fail!")
                }
            })
        })

        function if_collected() {   // ajax函数
            var result = '';    // 先定义个值，方便下面赋值
            $.ajax({
                async:false,    // 这个需要写上
                url:'/api/collection/ifCollected?userId=' + userId + '&itemId=' + itemId,
                type:'get',
                dataType:'json',
                data: JSON.stringify(''),
                success:function (data) {
                    result = data.msg;   // 赋值给刚才定义的值
                }
            });
            console.info("前端获取判断结果：ifCollected="+result)
            return result
        }

        $('#btn_collect').click(function () {

            // 现在是通过按钮本身的状态来判断是收藏还是取消收藏，如果项目重新启动,按钮状态和数据库状态会出现不一致
            // 目前数据库里没有该商品收藏时，也可能进行取消收藏操作，导致抛异常
            // 可以先写一个请求访问后端数据库，获取是否存在于数据库收藏中，存在则取消收藏，不存在则收藏
            // 已实现

            if (if_collected()=='false') {
                $.ajax({
                    type: 'POST',
                    dataType: 'json',
                    url: '/api/collection/add?userId=' + userId + '&itemId=' + itemId,
                    contentType: 'application/json',
                    traditional: true,
                    data: JSON.stringify(''),
                    success: function (data) {
                        if (data.code == 0) {
                            layer.msg('收藏成功！')
                            $('#btn_collect_icon').removeClass('glyphicon-star-empty glyphicon-star')
                            $('#btn_collect_icon').addClass('glyphicon glyphicon-star')
                        } else {
                            layer.msg(data.msg)
                        }
                    },
                    error: function (data) {
                    }
                })

            } else {
                $.ajax({
                    type: 'POST',
                    dataType: 'json',
                    url: '/api/collection/delete?userId=' + userId + '&itemId=' + itemId,
                    contentType: 'application/json',
                    traditional: true,
                    data: JSON.stringify(''),
                    success: function (data) {
                        if (data.code == 0) {
                            layer.msg('取消收藏成功！')
                            $('#btn_collect_icon').removeClass('glyphicon glyphicon-star')
                            $('#btn_collect_icon').addClass('glyphicon glyphicon-star-empty')
                        } else {
                            layer.msg(data.msg)
                        }
                    },
                    error: function (data) {
                    }
                })
            }
        })

        var followeeId = 0
        followeeId = [[${item.user.id}]]

        function if_followed() {   // ajax函数
            var result = '';    // 先定义个值，方便下面赋值
            $.ajax({
                async:false,    // 这个需要写上
                url:'/api/user/ifFollowed?followerId=' + userId + '&followeeId=' + followeeId,
                type:'get',
                dataType:'json',
                data: JSON.stringify(''),
                success:function (data) {
                    result = data.msg;   // 赋值给刚才定义的值
                }
            });
            console.info("前端获取判断结果：ifFollowed="+result)
            return result
        }

        // 如果未关注就关注，已经关注了就取关
        // followerId为当前登录用户id
        $('#btn_follow').click(function () {

        // 现在是通过按钮本身的状态来判断是关注还是取消关注，如果项目重新启动,按钮状态和数据库状态会出现不一致
        // 目前数据库里没有该用户关注时，也可能进行取消关注操作，导致抛异常

        // 可以先写一个请求访问后端数据库，获取是否存在于数据库中，存在则取消关注，不存在则关注 通过if_followed函数判断
        // 已实现


        if (if_followed()=='false') {
            $.ajax({
                type: 'POST',
                dataType: 'json',
                    url: '/api/user/follow?followerId=' + userId + '&followeeId=' + followeeId,
                contentType: 'application/json',
                traditional: true,
                data: JSON.stringify(''),
                success: function (data) {
                    if (data.code == 0) {
                        layer.msg('关注成功！')
                        $('#btn_follow_icon').removeClass('glyphicon-star-empty glyphicon-star')
                        $('#btn_follow_icon').addClass('glyphicon glyphicon-star')
                    } else {
                        layer.msg(data.msg)
                    }
                },
                error: function (data) {
                }
            })

        } else {
            $.ajax({
                type: 'POST',
                dataType: 'json',
                url: '/api/user/unfollow?followerId=' + userId + '&followeeId=' + followeeId,
                contentType: 'application/json',
                traditional: true,
                data: JSON.stringify(''),
                success: function (data) {
                    if (data.code == 0) {
                        layer.msg('取消关注成功！')
                        $('#btn_follow_icon').removeClass('glyphicon glyphicon-star')
                        $('#btn_follow_icon').addClass('glyphicon glyphicon-star-empty')
                    } else {
                        layer.msg(data.msg)
                    }
                },
                error: function (data) {
                }
            })
        }}
        )

        //设置顶部栏的登录/退出按钮和用户名显示

        function load_data() {

            var theme = localStorage.getItem('username')
            var userId = localStorage.getItem('userId')

            console.log(localStorage.getItem('username'))
            console.log(localStorage.getItem('userId'))
            if (theme == null || theme == '') {
                $('#login_logout').text('登录')
                $('#uname').text('')
                $('#wants').hide()
                $('release').hide()
                $('#cart').hide()
            } else {
                $('#login_logout').text('退出')
                $('#login_logout').attr('href', '/logout')
                $('#uname').text(theme)
                $('#wants').show()
                $('#wants').attr('href', '/api/wants/release?userId=' + userId)
                $('#release').show()
                $('#release').attr('href', '/release')
                $('#cart').show()
                $('#cart').attr('href', '/api/cart/all?userId=' + userId)
                $('#uname').attr('href', '/api/user/info?userId=' + userId)
            }


        }
    })
</script>
<script th:inline="javascript">
    function load_collect() {
        var isCollected = [[${inCollection}]];
        console.log(isCollected);
        if (isCollected == false) {
            $('#btn_collect_icon').removeClass('glyphicon-star-empty glyphicon-star')
            $('#btn_collect_icon').addClass('glyphicon glyphicon-star-empty')
        } else {
            $('#btn_collect_icon').removeClass('glyphicon-star-empty glyphicon-star')
            $('#btn_collect_icon').addClass('glyphicon glyphicon-star')
        }
    }

</script>
</body>
</html>
